<template>
  <div class="insp">
    <div class="insp-header">
      <div class="flexBetween">
        <div class="flex insp-header-left">
          <el-select
            clearable
            v-model="bridgeValue"
            placeholder="请选择桥梁"
            size="small"
            class="mRight10"
          >
            <el-option
              v-for="item in bridgeOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
          <el-input
            placeholder="请输入名称"
            v-model="name"
            size="small"
            style="width: 230px;"
            class="mRight10"
          >
          </el-input>
          <el-button type="primary" size="small" @click="queryForPage(1)">
            查询
          </el-button>
        </div>
      </div>
    </div>

    <div class="insp-content">
      <div class="insp-table">
        <el-table
          :data="tableData"
          :header-cell-style="{
            background: '#8595B9',
            color: '#fff',
            height: '44px'
          }"
          max-height="660px"
          :expand-row-keys="expandsRowKeys"
          @expand-change="handleExpand"
          :row-key="getRowKeys"
        >
          <el-table-column type="expand">
            <template slot-scope="props">
              <div>
                <el-table
                  ref="multipleTable"
                  :data="childTableData"
                  :header-cell-style="{
                    color: '#999',
                    height: '44px'
                  }"
                  style="width: 100%; border: 1px solid #EBEEF5; border-bottom:0"
                  class="insp-table-expand"
                  @selection-change="handleSelectionChange"
                >
                  <el-table-column
                    type="selection"
                    width="55"
                  ></el-table-column>
                  <el-table-column
                    label="报警级别"
                    property="alarmLever"
                    show-overflow-tooltip
                  >
                    <template slot-scope="scope">
                      <label :class="['insp-table-label']">
                        {{
                          scope.row.alarmLever === 1
                            ? "一级报警"
                            : scope.row.alarmLever === 2
                            ? "二级报警"
                            : scope.row.alarmLever === 3
                            ? "三级报警"
                            : scope.row.alarmLever === 4
                            ? "四级报警"
                            : ""
                        }}
                      </label>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="报警值"
                    prop="alarmValue"
                    show-overflow-tooltip
                  >
                  </el-table-column>
                  <el-table-column
                    label="报警时间"
                    prop="alarmDate"
                    show-overflow-tooltip
                  >
                  </el-table-column>
                  <el-table-column
                    label="处理状态"
                    property="state"
                    show-overflow-tooltip
                  >
                    <template slot-scope="scope">
                      <label
                        :class="[
                          'insp-table-label',
                          statusClass(scope.row.state)
                        ]"
                      >
                        {{ statusText(scope.row.state) }}
                      </label>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="处理内容"
                    prop="content"
                    show-overflow-tooltip
                  >
                  </el-table-column>
                </el-table>
                <div class="insp-page">
                  <el-pagination
                    background
                    layout="prev, pager, next"
                    :current-page.sync="currentPage_child"
                    :hide-on-single-page="false"
                    @current-change="handlePageChange_child"
                    :page-size="pageSize_child"
                    :total="recordsTotal_child"
                  >
                  </el-pagination>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="桥梁名称"
            prop="bridgeName"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column label="设备名称" prop="sname" show-overflow-tooltip>
          </el-table-column>
          <el-table-column label="设备编号" prop="code" show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            label="监测类型"
            prop="dataType"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            label="报警开始时间"
            prop="startTime"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            label="报警结束时间"
            prop="endTime"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template slot-scope="scope">
              <el-tooltip content="数据回溯">
                <el-button
                  type="text"
                  icon="el-icon-time"
                  @click="handleTime(scope.row)"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="批处理">
                <el-button
                  type="text"
                  icon="el-icon-s-operation"
                  @click="handleDo"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
          <template slot="empty">
            <span style="color: #969799;">暂无报警</span>
          </template>
        </el-table>
      </div>

      <div class="insp-page">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page.sync="currentPage"
          :hide-on-single-page="false"
          @current-change="handlePageChange"
          :page-size="pageSize"
          :total="recordsTotal"
        >
        </el-pagination>
      </div>
    </div>

    <!--数据回溯弹框-->
    <vx-popup
      title="数据回溯"
      width="800px"
      @close="cancelFormSubmit"
      :active.sync="dialogTimeVisible"
      @confirmPopup="cancelFormSubmit"
      @cancelPopup="cancelFormSubmit"
    >
      <div style="display:inline-block">
        <el-select
          v-model="ruleTime.bridgeId"
          placeholder="请选择"
          size="small"
          style="width:120px;margin-right:10px;"
          :disabled="true"
        >
          <el-option
            v-for="item in bridgeOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
        <el-input
          type="text"
          v-model="ruleTime.code"
          size="small"
          :disabled="true"
          style="width:120px;margin-right:10px;"
        ></el-input>
        <el-date-picker
          size="small"
          value-format="yyyy-MM-dd HH:mm"
          format="yyyy-MM-dd HH:mm"
          v-model="ruleTime.time"
          type="datetime"
          placeholder="回溯时间"
          style="width:180px;margin-right:10px;"
          clearable
        >
        </el-date-picker>
        <el-button type="primary" size="small" @click="queryTime()">
          查询
        </el-button>
      </div>
      <div class="insp-healthy">
        <div ref="lineChart" class="insp-healthy-echart"></div>
      </div>
    </vx-popup>

    <!--批处理弹框-->
    <vx-popup
      title="报警批处理"
      width="600px"
      @close="cancelHandle"
      :active.sync="dialogHandleVisible"
      @confirmPopup="submitHandle"
      @cancelPopup="cancelHandle"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        class="demo-ruleForm"
      >
        <el-form-item label="结果 :" prop="state">
          <el-radio-group v-model="ruleForm.state">
            <el-radio :label="0">未处理</el-radio>
            <el-radio :label="1">处理中</el-radio>
            <el-radio :label="2">已处理</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="描述 :" prop="content">
          <el-input
            type="textarea"
            placeholder="请输入..."
            maxlength="200"
            rows="3"
            v-model="ruleForm.content"
            style="width:380px"
            show-word-limit
          >
          </el-input>
        </el-form-item>
      </el-form>
    </vx-popup>
  </div>
</template>
<script>
import echarts from "echarts";
import moment from "moment";
export default {
  data() {
    return {
      getRowKeys(row) {
        return row.id;
      },
      name: "",
      // bridgeValue: "",
      bridgeValue: localStorage.getItem('ownId') ? localStorage.getItem('ownId'): '',
      bridgeOptions: [],
      pageSize: 14,
      currentPage: 1,
      recordsTotal: 0,
      tableData: [],
      childTableData: [],
      pageSize_child: 6,
      currentPage_child: 1,
      recordsTotal_child: 0,
      expandsRowKeys: [],
      multipleSelection: [],
      dialogHandleVisible: false,
      ruleForm: {
        state: 0,
        content: ""
      },
      rules: {
        state: [
          {
            required: true,
            message: "请选择",
            trigger: "change"
          }
        ],
        content: [
          {
            required: true,
            message: "请输入",
            trigger: "blur"
          }
        ]
      },
      dialogTimeVisible: false,
      ruleTime: {
        bridgeId: "",
        code: "",
        time: ""
      },
      timeData: [],
      line: null,
      rowBridgeId: "",
      rowId: "",
      rowCode: ""
    };
  },
  created() {
    this.queryBridgeList();

    this.queryForPage(1);
  },
  mounted() {
    window.addEventListener("resize", () => {
      if (this.line) {
        this.line.resize();
      }
    });
  },
  methods: {
    queryForPage(pageIndex) {
      if (pageIndex && pageIndex === 1) {
        this.currentPage = 1;
      }
      let _params = {
        pageSize: this.pageSize,
        pageNum: this.currentPage
      };

      if (this.bridgeValue) {
        _params.bridgeId = this.bridgeValue;
      }
      if (this.name) {
        _params.name = this.name;
      }

      this.$api.healthMonitor.querySensorForPage(_params).then(response => {
        if (response.data.success) {
          this.tableData = response.data.data;
          this.recordsTotal = response.data.recordsTotal;
        }
      });
    },
    handlePageChange(currentPage) {
      this.currentPage = currentPage;
      this.queryForPage();
    },
    queryBridgeList() {
      this.$api.bridge.AllTheBridges().then(response => {
        if (response.data.success) {
          this.bridgeOptions = response.data.data[0];
        }
      });
    },
    handleExpand(row, expandedRows) {
      if (expandedRows.length) {
        this.expandsRowKeys = [];
        if (row) {
          this.expandsRowKeys.push(row.id);
          this.rowBridgeId = row.bridgeId;
          this.rowCode = row.code;
          this.rowId = row.id;
          this.queryByCodeAndBridgeId(row.bridgeId, row.code, row.id, 1);
        }
      } else {
        this.expandsRowKeys = [];
      }
    },
    queryByCodeAndBridgeId(bridgeId, code, id, pageIndex) {
      this.$api.healthMonitor
        .queryByCodeAndBridgeId({
          bridgeId,
          code,
          pageNum: pageIndex,
          pageSize: this.pageSize_child
        })
        .then(response => {
          if (response.data.success) {
            this.childTableData = response.data.data;
            this.recordsTotal_child = response.data.recordsTotal;
          }
        });
    },
    handlePageChange_child(currentPage) {
      this.currentPage_child = currentPage;
      this.queryByCodeAndBridgeId(
        this.rowBridgeId,
        this.rowCode,
        this.rowId,
        currentPage
      );
    },
    emptyForm() {
      this.$refs["ruleForm"].resetFields();
      this.ruleForm = {
        state: 0,
        content: ""
      };
    },
    handleDo(val) {
      if (this.multipleSelection.length < 1) {
        this.$vs.notify({
          text: "请选择要处理的报警数据",
          color: "danger"
        });
        return false;
      }
      this.emptyForm();
      this.dialogHandleVisible = true;
    },
    cancelHandle() {
      this.dialogHandleVisible = false;
    },
    submitHandle() {
      this.$refs.ruleForm.validate(async valid => {
        if (!valid) {
          return false;
        }
        const _ids = this.multipleSelection.map(item => item.id);
        let _params = {
          ids: _ids,
          state: this.ruleForm.state,
          content: this.ruleForm.content
        };
        this.$api.healthMonitor.batchDatas(_params).then(response => {
          if (response.data.success) {
            this.$vs.notify({
              text: "操作成功",
              color: "success"
            });
            this.expandsRowKeys = [];
            this.dialogHandleVisible = false;
            this.queryForPage(1);
          }
        });
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleTime(row) {
      this.ruleTime.time = "";
      this.ruleTime.bridgeId = row.bridgeId;
      this.ruleTime.code = row.code;
      this.dialogTimeVisible = true;
    },
    cancelFormSubmit() {
      this.dialogTimeVisible = false;
    },
    queryTime() {
      let _params = {
        code: this.ruleTime.code,
        bridgeId: this.ruleTime.bridgeId,
        time: this.ruleTime.time
      };
      this.$api.healthMonitor.dataBack(_params).then(response => {
        if (response.data.success) {
          this.timeData = response.data.data.data;
          this.drawLine(this.timeData);
        }
      });
    },
    drawLine(timeData) {
      const _xAxisData =
        timeData.length > 0
          ? timeData.map(item => this.formateDate(item.time))
          : [];
      const _seriesData = timeData.map(item => parseInt(item.value));
      this.line = new echarts.init(this.$refs.lineChart);
      this.line.setOption({
        grid: {
          top: "10%",
          right: "5%",
          left: "5%",
          bottom: "20%"
        },
        dataZoom:
          timeData.length > 8
            ? [
                {
                  show: true,
                  height: 12,
                  xAxisIndex: [0],
                  bottom: 0,
                  start: 0,
                  end: 40,
                  handleSize: "110%",
                  handleStyle: {
                    color: "#5B3AAE"
                  },
                  textStyle: {
                    color: "rgba(204,187,225,0.5)"
                  },
                  fillerColor: "rgba(105, 158, 229,0.2)",
                  borderColor: "rgba(105, 158, 229,0.3)",
                  showDetail: false
                },
                {
                  type: "inside",
                  show: true,
                  height: 12,
                  start: 1,
                  end: 35
                }
              ]
            : [],
        tooltip: {
          trigger: "axis"
        },
        xAxis: [
          {
            type: "category",
            data: _xAxisData.map(item => item.replace(" ", "\n")),
            axisLine: {
              show: true,
              lineStyle: {
                color: "#E5E6EB"
              }
            },
            axisTick: {
              show: false
            },
            splitLine: {
              show: true,
              lineStyle: {
                color: "#E5E6EB"
              }
            },
            boundaryGap: false,
            axisLabel: {
              color: "#A7A6AF",
              fontSize: 12
            }
          }
        ],
        yAxis: [
          {
            type: "value",
            axisTick: {
              show: false
            },
            splitNumber: 4,
            splitLine: {
              show: false
            },
            splitArea: {
              show: true,
              areaStyle: {
                color: ["#F5F6FA", "#fff"]
              }
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: "#E5E6EB"
              }
            },
            axisLabel: {
              color: "#A7A6AF",
              fontSize: 12
            }
          }
        ],
        series: [
          {
            data: _seriesData,
            type: "line",
            symbol: "emptyCircle",
            symbolSize: 8,
            lineStyle: {
              color: "#699EE5",
              shadowBlur: 12,
              shadowColor: "rgb(33,148,246,0.5)",
              shadowOffsetX: 1,
              shadowOffsetY: 1
            },
            itemStyle: {
              color: "#699EE5",
              borderWidth: 1
            }
          }
        ]
      });
    },
    statusClass(type) {
      switch (type) {
        case 0:
          return "planStatusB";
        case 1:
          return "planStatusA";
        case 2:
          return "";
      }
    },
    statusText(type) {
      switch (type) {
        case 0:
          return "未处理";
        case 1:
          return "处理中";
        case 2:
          return "已处理";
      }
    },
    formateDate(_date) {
      let date = new Date(_date);
      let YY = date.getFullYear() + "-";
      let MM =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      let DD = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      let hh =
        (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
      let mm =
        (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
        ":";
      let ss =
        date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      return YY + MM + DD + " " + hh + mm + ss;
    }
  }
};
</script>
<style scoped lang="scss">
@import "@/views/inspection/insp.scss";

/deep/.el-table__header tr,
/deep/.el-table__header th {
  padding: 0;
  height: 44px;
}

/deep/.el-table td,
/deep/.el-table th {
  text-align: center;
  font-size: 14px;
}

/deep/.el-table th {
  font-weight: 500;
  color: #fff;
}

/deep/.el-table td {
  font-weight: 400;
  color: #444;
  padding: 0;
  height: 44px;
  line-height: 44px;
}

/deep/.el-table--striped .el-table__body tr.el-table__row--striped td {
  background: #f1f5fc;
}

/deep/.el-table__expanded-cell {
  padding: 20px !important;
}
</style>
